package com.rzjm.exercise.module.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.service.impl.BaseServiceImpl;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.StringUtils;
import com.rzjm.exercise.module.dao.CkTerminalDao;
import com.rzjm.exercise.module.dao.DeviceDao;
import com.rzjm.exercise.module.dao.DeviceNodeDao;
import com.rzjm.exercise.module.dao.TerminalTemperatureDao;
import com.rzjm.exercise.module.domain.Device;
import com.rzjm.exercise.module.domain.DeviceNode;
import com.rzjm.exercise.module.domain.TerminalTemperature;
import com.rzjm.exercise.module.service.TerminalTemperatureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class TerminalTemperatureServiceImpl extends BaseServiceImpl<TerminalTemperatureDao, TerminalTemperature> implements TerminalTemperatureService {

    @Resource
    private CkTerminalDao ckTerminalDao;
    @Resource
    private TerminalTemperatureDao temperatureDao;
    @Resource
    private DeviceNodeDao deviceNodeDao;
    @Resource
    private DeviceDao deviceDao;

    @Value("${projecturl.imgurl}")
    private String imgurl;

    @Override
    public List<TerminalTemperature> getListByTerminalId(Map<String, Object> map) {
        List<TerminalTemperature> list = temperatureDao.getListByTerminalId(map);
        return list;
    }

    @Override
    public Map<String, Object> getChartData(Map<String, Object> map) {
        Map<String, Object> mapReturn = new HashMap<>();
        List<TerminalTemperature> list = temperatureDao.getListByTerminalId(map);
        if(list!=null && list.size() > 0){
            List<String> times = new ArrayList<>();
            List<String> values = new ArrayList<>();
            for (TerminalTemperature temperature : list){
                times.add(temperature.getCreateTime().toString());
                values.add(temperature.getWendu().toString());
            }
            mapReturn.put("times",times);
            mapReturn.put("values",values);
        }
        return mapReturn;
    }


    @Override
    public Map<String, Object> getChartData(Integer deviceId, String beginDate, String endDate, Integer positionType) {
        double maxValue = 0d;
        Map<String,Object> mapReturn = new HashMap<>();

        List<String> times = new ArrayList<>();
        List<String> values = new ArrayList<>();
        List<String> values1 = new ArrayList<>();

//        List<DeviceNode> nodes = deviceNodeDao.selectListByColumn("device_id", deviceId);
        QueryWrapper<DeviceNode> deviceNodeQueryWrapper = new QueryWrapper<>();
        deviceNodeQueryWrapper.eq("device_id", deviceId);
        if(positionType!=null && positionType != 0){
            deviceNodeQueryWrapper.eq("position_type",positionType);
        }
        List<DeviceNode> nodes = deviceNodeDao.selectList(deviceNodeQueryWrapper);

        if(CollUtil.isNotEmpty(nodes)){

            for(int i = 0; i < 24; i++){
                String hour = String.format("%02d", i);
//            List<TerminalTemperature> temperatures = temperatureDao.selectList(qw);
//            for (TerminalTemperature temperature : temperatures){
//                times.add(DateUtils.getSimpleTime(temperature.getCreateTime()));
//                values.add(temperature.getWendu().toString());
//            }
                times.add(hour + ":00");

                int index = 0;
                for (DeviceNode node : nodes){

                    QueryWrapper<TerminalTemperature> qw = new QueryWrapper<>();
                    qw.eq("device_id",deviceId);
                    qw.eq("node_index", node.getNodeIndex());
                    qw.eq("ins_index", node.getInsIndex());
                    qw.gt("wendu", 0);
                    qw.between("create_time",beginDate + " "+ hour +":00:00",endDate + " "+  hour +":59:59");
                    qw.orderByAsc("wendu");
                    qw.last("limit 1");
                    TerminalTemperature temperature = temperatureDao.selectOne(qw);
                    if(temperature != null){
                        if(index == 0){
                            values.add(temperature.getWendu().toString());
                            values1.add("0");
                        }else{
                            values.add("0");
                            values1.add(temperature.getWendu().toString());
                        }
                    }
                    index++;
                }
            }
        }

//        QueryWrapper<TerminalTemperature> qw = new QueryWrapper<>();
//        qw.eq("device_id",deviceId);
////        String hour = String.format("%02d", i);
//        qw.between("create_time",beginDate + " 00:00:00",endDate + " 23:59:59");
////        qw.orderByAsc("wendu");
//        List<TerminalTemperature> temperatures = temperatureDao.selectList(qw);
//        for (TerminalTemperature temperature : temperatures){
//            times.add(DateUtils.getSimpleTime(temperature.getCreateTime()));
//            values.add(temperature.getWendu().toString());
//        }

        mapReturn.put("times",times);
        mapReturn.put("values",values);
        mapReturn.put("values1",values1);
        mapReturn.put("count",times.size());
        mapReturn.put("maxValue",maxValue);
        mapReturn.put("minValue",maxValue);

        mapReturn.put("beginDate",beginDate);
        mapReturn.put("endDate",endDate);
        return mapReturn;
    }

    @Override
    public Map<String,Object> getChartDataByShopDevice(Integer shopId, int dataType, int deviceType, String searchDate, Integer positionType, Integer feedId,String feedIds,String nodeIds) {
        double maxValue = 0d;
        Map<String,Object> map = new HashMap<>();

        String beginDate = "";
        String endDate = "";
        List<String> days = new ArrayList<>();
        if (StringUtils.isNotBlank(searchDate)){
            days.add(searchDate);
        }else if(dataType == 0){
            beginDate = DateUtils.getDay();
            endDate = DateUtils.getDay();
            days.add(DateUtils.getDay());
        }else{
            days = DateUtils.getBeforeSevenDay();
        }


        List<String> deviceNames = new ArrayList<>();
        List<Map<String,Object>> dataList = new ArrayList<>();
        QueryWrapper<Device> qw = new QueryWrapper<>();
        qw.eq("shop_id", shopId);
        if (positionType != null && positionType != 0){
            qw.eq("position_type", positionType);
        }
        List<Device> list = deviceDao.selectList(qw);
        String[] nodeIdsArr = null;
        String[] feedIdsArr = null;
        if (StringUtils.isNotEmpty(nodeIds)){
            nodeIdsArr = nodeIds.split("-");
        }
        if (StringUtils.isNotEmpty(feedIds)){
            feedIdsArr = feedIds.split("-");
        }
        if(CollUtil.isNotEmpty(list)){
            for (Device device : list){
                deviceNames.add(device.getDeviceName());
                Map<String,Object> mapReturn = new HashMap<>();
                List<String> times = new ArrayList<>();
                List<String> values = new ArrayList<>();

                QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
                qwNode.eq("device_id", device.getId());
                qwNode.eq("device_type", deviceType);
                List<DeviceNode> nodes = deviceNodeDao.selectList(qwNode);
                if(CollUtil.isNotEmpty(nodes)){

                    for (String day : days){
                        for (DeviceNode node : nodes){
                            QueryWrapper<TerminalTemperature> qwTemp = new QueryWrapper<>();
                            qwTemp.eq("device_id",device.getId());
                            qwTemp.eq("node_index", node.getNodeIndex());
                            qwTemp.eq("ins_index", node.getInsIndex());
                            qwTemp.eq("is_unqualified", 0);
                            if (feedId != null && feedId != 0){
                                qwTemp.eq("feed_id", feedId);
                            }
                            if (nodeIdsArr != null){
                                for (int j = 0; j < nodeIdsArr.length; j++){
                                    if (node.getId().toString().equals(nodeIdsArr[j])){
                                        qwTemp.in("feed_id",feedIdsArr[j].split(","));
                                    }
                                }
                            }
                            qwTemp.gt("wendu", node.getMinShowValue());
                            qwTemp.between("create_time",day + " 00:00:00" ,day + " 23:59:59");
                            qwTemp.orderByAsc("create_time");
                            List<TerminalTemperature> temperatures = temperatureDao.selectList(qwTemp);
                            List<String> timeList = temperatures.stream().map(t -> DateUtils.parseDateToStr("MM-dd HH:mm:ss", t.getCreateTime())).collect(Collectors.toList());
                            List<String> valueList = temperatures.stream().map(t -> t.getWendu() == null ? "" : t.getWendu().toString()).collect(Collectors.toList());
                            times.addAll(timeList);
                            values.addAll(valueList);
//                            for(int i = 0; i < 24; i++){
//                                String hour = String.format("%02d", i);
//                                String ss = day.substring(5, day.length());
//
//                                String[] showMin = { ":00", ":10", ":20", ":30", ":40",":50" };
//                                String[] beginTime = { ":00:00", ":10:00", ":20:00", ":30:00", ":40:00",":50:00" };
//                                String[] endTime = { ":09:59", ":19:59", ":29:59", ":39:59", ":49:59",":59:59" };
//                                for (int j = 0;j < beginTime.length ;j++){
//
//                                    times.add(ss + " " + hour + showMin[j]);
//
//                                    QueryWrapper<TerminalTemperature> qwTemp = new QueryWrapper<>();
//                                    qwTemp.eq("device_id",device.getId());
//                                    qwTemp.eq("node_index", node.getNodeIndex());
//                                    qwTemp.eq("ins_index", node.getInsIndex());
//                                    qwTemp.gt("wendu", node.getMinShowValue());
//                                    qwTemp.between("create_time",day + " " + hour + beginTime[j],day + " " +  hour + endTime[j]);
//                                    qwTemp.orderByAsc("wendu");
//                                    qwTemp.last("limit 1");
//                                    TerminalTemperature temperature = temperatureDao.selectOne(qwTemp);
//                                    if(temperature != null){
//                                        values.add(temperature.getWendu().toString());
//                                    }else{
////                                    Calendar cal = Calendar.getInstance();
////                                    int hourNow = cal.get(Calendar.HOUR_OF_DAY);
////                                    if(hourNow >= Integer.parseInt(hour)){
//////                                        times.add(ss + " " + hour + ":00");
////                                    }
//                                        values.add("");
//                                    }
//                                }
//
//
//
//
//
////                                times.add(ss + " " + hour + ":30");
////
////                                QueryWrapper<TerminalTemperature> qwTemp1 = new QueryWrapper<>();
////                                qwTemp1.eq("device_id",device.getId());
////                                qwTemp1.eq("node_index", node.getNodeIndex());
////                                qwTemp1.eq("ins_index", node.getInsIndex());
////                                qwTemp1.gt("wendu", node.getMinShowValue());
////                                qwTemp1.between("create_time",day + " " + hour + ":30:00",day + " " +  hour + ":59:59");
////                                qwTemp1.orderByAsc("wendu");
////                                qwTemp1.last("limit 1");
////                                TerminalTemperature temperature1 = temperatureDao.selectOne(qwTemp1);
////                                if(temperature1 != null){
//////                                    times.add(ss + " " + hour + ":30");
////                                    values.add(temperature1.getWendu().toString());
////                                }else{
//////                                    Calendar cal = Calendar.getInstance();
//////                                    int hourNow = cal.get(Calendar.HOUR_OF_DAY);
//////                                    if(hourNow >= Integer.parseInt(hour)){
////////                                        times.add(ss + " " + hour + ":30");
//////                                    }
////                                    values.add("");
////                                }
//                            }
                        }
                    }
                }

                mapReturn.put("times",times);
                mapReturn.put("values",values);
//                mapReturn.put("values1",values1);
                mapReturn.put("count",times.size());
//                mapReturn.put("maxValue",maxValue);
//                mapReturn.put("minValue",maxValue);

//                map.put("beginDate",beginDate);
//                map.put("endDate",endDate);

                dataList.add(mapReturn);
            }
        }

        map.put("dataList",dataList);
        map.put("deviceNames",deviceNames);
        return map;
    }

    @Override
    public Map<String, Object> getChartDataByDevice(Integer deviceId, int dataType, int deviceType,int shopId,
                                                    int deviceShowType, String searchDate ,Integer positionType, Integer feedId,String feedIds,String nodeIds) {

        Map<String,Object> map = new HashMap<>();

        List<String> days = new ArrayList<>();
        if (StringUtils.isNotBlank(searchDate)){
            days.add(searchDate);
        }else if(dataType == 0){
            days.add(DateUtils.getDay());
        }else{
            days = DateUtils.getBeforeSevenDay();
        }

        List<String> deviceNames = new ArrayList<>();
        List<Map<String,Object>> dataList = new ArrayList<>();
//        Device device = deviceDao.selectById(deviceId);
//        if(device != null){


            QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
            if(deviceShowType == 0){
                qwNode.eq("device_id", deviceId);
            }else{
                qwNode.eq("shop_id", shopId);
            }
            qwNode.eq("device_type", deviceType);
            if (positionType != null && positionType != 0){
                qwNode.eq("position_type", positionType);
            }
            List<DeviceNode> nodes = deviceNodeDao.selectList(qwNode);
            String[] nodeIdsArr = null;
            String[] feedIdsArr = null;
            if (StringUtils.isNotEmpty(nodeIds)){
                nodeIdsArr = nodeIds.split("-");
            }
            if (StringUtils.isNotEmpty(feedIds)){
                feedIdsArr = feedIds.split("-");
            }
            if(CollUtil.isNotEmpty(nodes)){
                for (DeviceNode node : nodes){
                    Map<String,Object> mapReturn = new HashMap<>();
                    List<String> times = new ArrayList<>();
                    List<Map<String, Object>> values = new ArrayList<>();
                    String terminalName = node.getTerminalName();
                    deviceNames.add(terminalName);

                    for (String day : days){
                        QueryWrapper<TerminalTemperature> qwTemp = new QueryWrapper<>();
                        qwTemp.eq("device_id", node.getDeviceId());
                        qwTemp.eq("node_index", node.getNodeIndex());
                        qwTemp.eq("ins_index", node.getInsIndex());
                        qwTemp.eq("is_unqualified", 0);
                        qwTemp.gt("wendu", node.getMinShowValue());
                        if (feedId != null && feedId != 0){
                            qwTemp.eq("feed_id", feedId);
                        }
                        if (nodeIdsArr != null){
                            for (int j = 0; j < nodeIdsArr.length; j++){
                                if (node.getId().toString().equals(nodeIdsArr[j])){
                                    qwTemp.in("feed_id",feedIdsArr[j].split(","));
                                }
                            }
                        }
                        qwTemp.between("create_time",day + " 00:00:00" ,day + " 23:59:59");
                        qwTemp.orderByAsc("create_time");
                        List<TerminalTemperature> temperature = temperatureDao.selectList(qwTemp);
                        List<TerminalTemperature> temperatureCopy = temperature;
//                        List<String> timeList = temperature.stream().map(t -> DateUtils.parseDateToStr("MM-dd HH:mm:ss", t.getCreateTime())).collect(Collectors.toList());
//                        List<String> valueList = temperature.stream().map(t -> t.getWendu() == null ? "" : t.getWendu().toString()).collect(Collectors.toList());
//                        times.addAll(timeList);
//                        values.addAll(valueList);
                        String bj = "";
                        for (int k = 0;k < temperature.size(); k++){
                            TerminalTemperature tem = temperature.get(k);
                            String name = "";
                            if (StringUtils.isNotEmpty(tem.getFeedName())){
                                name = "饲料：" + tem.getFeedName();
                            }
                            if (k == 0){
                                bj = tem.getFeedName();
                            }
                            Map<String, Object> temmap = new HashMap<>();
                            if (tem.getFeedName() == null && bj != null){
                                bj = null;

                                // 加空值分段
                                for (int n = 0; n < 10; n++){
                                    Map<String, Object> temmap1 = new HashMap<>();
                                    temmap1.put("name", "");
                                    temmap1.put("value", "-");
                                    values.add(temmap1);
                                    times.add("-");
                                }

                                temmap.put("name", name);
                                temmap.put("value", tem.getWendu());
                                values.add(temmap);
                                times.add(DateUtils.parseDateToStr("MM-dd HH:mm:ss", tem.getCreateTime()));
                            }else if (tem.getFeedName() == null && bj == null){
                                temmap.put("name", name);
                                temmap.put("value", tem.getWendu());
                                values.add(temmap);
                                times.add(DateUtils.parseDateToStr("MM-dd HH:mm:ss", tem.getCreateTime()));
                            }else if (tem.getFeedName() != null && bj == null){
                                bj = tem.getFeedName();
                                // 加空值分段
                                for (int n = 0; n < 10; n++){
                                    Map<String, Object> temmap1 = new HashMap<>();
                                    temmap1.put("name", "");
                                    temmap1.put("value", "-");
                                    values.add(temmap1);
                                    times.add("-");
                                }

                                temmap.put("name", name);
                                temmap.put("value", tem.getWendu());
                                values.add(temmap);
                                times.add(DateUtils.parseDateToStr("MM-dd HH:mm:ss", tem.getCreateTime()));
                            }else if (bj.equals(tem.getFeedName())){

                                temmap.put("name", name);
                                temmap.put("value", tem.getWendu());
                                values.add(temmap);
                                times.add(DateUtils.parseDateToStr("MM-dd HH:mm:ss", tem.getCreateTime()));
                            }else if (!bj.equals(tem.getFeedName())){
                                // 加空值分段
                                for (int n = 0; n < 10; n++){
                                    Map<String, Object> temmap1 = new HashMap<>();
                                    temmap1.put("name", "");
                                    temmap1.put("value", "-");
                                    values.add(temmap1);
                                    times.add("-");
                                }
                                bj = tem.getFeedName();
                                temmap.put("name", name);
                                temmap.put("value", tem.getWendu());
                                values.add(temmap);
                                times.add(DateUtils.parseDateToStr("MM-dd HH:mm:ss", tem.getCreateTime()));
                            }

                        }


//                        for(int i = 0; i < 24; i++){
//
//                            String hour = String.format("%02d", i);
//                            String ss = day.substring(5, day.length());
//
//                            String[] showMin = { ":00", ":10", ":20", ":30", ":40",":50" };
//                            String[] beginTime = { ":00:00", ":10:00", ":20:00", ":30:00", ":40:00",":50:00" };
//                            String[] endTime = { ":09:59", ":19:59", ":29:59", ":39:59", ":49:59",":59:59" };
//                            for (int j = 0;j < beginTime.length ;j++) {
//
//                                times.add(ss + " " + hour + showMin[j]);
//                                QueryWrapper<TerminalTemperature> qwTemp = new QueryWrapper<>();
//                                qwTemp.eq("device_id", node.getDeviceId());
//                                qwTemp.eq("node_index", node.getNodeIndex());
//                                qwTemp.eq("ins_index", node.getInsIndex());
//                                qwTemp.gt("wendu", node.getMinShowValue());
//                                qwTemp.between("create_time",day + " " + hour + beginTime[j],day + " " +  hour + endTime[j]);
//                                qwTemp.orderByAsc("wendu");
//                                qwTemp.last("limit 1");
//                                TerminalTemperature temperature = temperatureDao.selectOne(qwTemp);
//                                if(temperature != null){
//                                    values.add(temperature.getWendu().toString());
//                                }else{
//                                    Calendar cal = Calendar.getInstance();
//                                    int hourNow = cal.get(Calendar.HOUR_OF_DAY);
//                                    if(hourNow >= Integer.parseInt(hour)){
////                                    values.add("");
//                                    }
//                                    values.add("");
//                                }
//
//                            }
////                            times.add(ss + " " + hour + ":00");
////                            QueryWrapper<TerminalTemperature> qwTemp = new QueryWrapper<>();
////                            qwTemp.eq("device_id", node.getDeviceId());
////                            qwTemp.eq("node_index", node.getNodeIndex());
////                            qwTemp.eq("ins_index", node.getInsIndex());
////                            qwTemp.gt("wendu", node.getMinShowValue());
////                            qwTemp.between("create_time",day + " " + hour + ":00:00",day + " " +  hour + ":29:59");
////                            qwTemp.orderByAsc("wendu");
////                            qwTemp.last("limit 1");
////                            TerminalTemperature temperature = temperatureDao.selectOne(qwTemp);
////                            if(temperature != null){
////                                values.add(temperature.getWendu().toString());
////                            }else{
////                                Calendar cal = Calendar.getInstance();
////                                int hourNow = cal.get(Calendar.HOUR_OF_DAY);
////                                if(hourNow >= Integer.parseInt(hour)){
//////                                    values.add("");
////                                }
////                                values.add("");
////                            }
////
////                            times.add(ss + " " + hour + ":30");
////
////                            QueryWrapper<TerminalTemperature> qwTemp1 = new QueryWrapper<>();
////                            qwTemp1.eq("device_id", node.getDeviceId());
////                            qwTemp1.eq("node_index", node.getNodeIndex());
////                            qwTemp1.eq("ins_index", node.getInsIndex());
////                            qwTemp1.gt("wendu", node.getMinShowValue());
////                            qwTemp1.between("create_time",day + " " + hour + ":30:00",day + " " +  hour + ":59:59");
////                            qwTemp1.orderByAsc("wendu");
////                            qwTemp1.last("limit 1");
////                            TerminalTemperature temperature1 = temperatureDao.selectOne(qwTemp1);
////                            if(temperature1 != null){
////                                values.add(temperature1.getWendu().toString());
////                            }else{
////                                Calendar cal = Calendar.getInstance();
////                                int hourNow = cal.get(Calendar.HOUR_OF_DAY);
////                                if(hourNow >= Integer.parseInt(hour)){
//////                                    values.add("");
////                                }
////                                values.add("");
////                            }
//                        }
                    }

                    mapReturn.put("times",times);
                    mapReturn.put("values",values);
//                mapReturn.put("values1",values1);
                    mapReturn.put("count",times.size());
                    mapReturn.put("nodeId",node.getId());
//                mapReturn.put("maxValue",maxValue);
//                mapReturn.put("minValue",maxValue);

//                map.put("beginDate",beginDate);
//                map.put("endDate",endDate);

                    dataList.add(mapReturn);
                }

            }
//        }
        map.put("dataList",dataList);
        map.put("deviceNames",deviceNames);
        return map;
    }

    @Override
    public Long getDeviceAvgData(Map<String, Object> temperatureMap) {
        return temperatureDao.getDeviceAvgInfo(temperatureMap);
    }

    @Override
    public List<TerminalTemperature> getTemperatureList(Map<String, Object> searchParams) {
        return temperatureDao.getTemperatureList(searchParams);
    }
}
